package mz.matafe.bolao

import org.codehaus.groovy.grails.plugins.springsecurity.RedirectUtils
import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import org.grails.plugins.springsecurity.service.AuthenticateService

import org.springframework.security.AuthenticationTrustResolverImpl
import org.springframework.security.DisabledException
import org.springframework.security.context.SecurityContextHolder as SCH
import org.springframework.security.ui.AbstractProcessingFilter
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter

/**
 * Login Controller.
 *
 * <p>Handle the system login
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
@Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
class LoginController {

    /** Authentication service.  */
    def authenticateService

    private final authenticationTrustResolver = new AuthenticationTrustResolverImpl()

    def index = {
        if (isLoggedIn()) {
            redirect uri: '/'
        }
        else {
            redirect action: auth, params: params
        }
    }

    /** Show the login page. */
    def auth = {
        nocache response
        if (isLoggedIn()) {
            redirect uri: '/'
            return
        }
        def config = authenticateService.securityConfig.security
        String postUrl = "${request.contextPath}${config.filterProcessesUrl}"
        render view: 'auth', model: [postUrl: postUrl]
    }

    // Login page (function|json) for Ajax access.
    def authAjax = {
        nocache(response)
        //this is example:
        render """
        <script type='text/javascript'>
        (function() {
                loginForm();
        })();
        </script>
        """
    }

    /** The Ajax success redirect url. */
    def ajaxSuccess = {
        nocache(response)
        render '{success: true}'
    }

    /** Show denied page. */
    def denied = {
        if (isLoggedIn() && authenticationTrustResolver.isRememberMe(SCH.context?.authentication)) {
            // have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
            redirect action: full, params: params
        }
    }

    /**
     * Login page for users with a remember-me cookie but
     * accessing a IS_AUTHENTICATED_FULLY page.
     */
    def full = {
        render view: 'auth', params: params,
            model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication)]
    }

    /** Denied page (data|view|json) for Ajax access. */
    def deniedAjax = {
        render "{error: 'access denied'}"
    }

    /** Login failed */
    def authfail = {
        def username = session[AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY]
        def msg = ''
        def exception = session[AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY]
        println exception
        if (exception) {
            if (exception instanceof DisabledException) {
                msg = "[$username] esta desabilitado."
            }
            else {
                msg = "Nome de usuário/senha invalidos! [$username]."
            }
        }
        if (isAjax()) {
            render "{error: '${msg}'}"
        }
        else {
            flash.message = msg
            redirect action: auth, params: params
        }
    }

    /** Check if logged in. */
    private boolean isLoggedIn() {
        return authenticateService.isLoggedIn()
    }

    /** Check if ajax. */
    private boolean isAjax() {
        return authenticateService.isAjax(request)
    }

    /** Cache controls */
    private void nocache(response) {
        response.setHeader('Cache-Control', 'no-cache') // HTTP 1.1
        response.addDateHeader('Expires', 0)
        response.setDateHeader('max-age', 0)
        response.setIntHeader ('Expires', -1) //prevents caching at the proxy server
        response.addHeader('cache-Control', 'private') //IE5.x only
    }
}
